package com.duan.common.handler;


import com.duan.common.annotations.ControllerLimitAnnotation;
import com.duan.common.exceptions.ServiceException;
import com.duan.common.utils.redis.RedisLimit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.atomic.AtomicInteger;


@Component
public class WebLimitIntercept implements WebMvcConfigurer {

    @Autowired
    private RedisLimit redisLimit;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new LimitIntercept())
                .addPathPatterns("/**");
    }

    AtomicInteger requestTimes = new AtomicInteger();

    class LimitIntercept implements HandlerInterceptor {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

            if (redisLimit == null) {
                throw new ServiceException("redisLimit为空");
            }

//            HandlerMethod handlerMethod = (HandlerMethod) handler;
//            ControllerLimitAnnotation  controllerLimitAnnotation = handlerMethod.getMethodAnnotation(ControllerLimitAnnotation.class);
//            if (controllerLimitAnnotation == null){
//                return true;
//            }

            if (!redisLimit.limit()) {
                System.out.println(">>>>> 当前 " + requestTimes.getAndSet(1) + " 请求显示");
                throw new ServiceException("当前并发太大redis限制啦请求");
            }

            System.out.println("<<<<<< 当前 " + requestTimes.getAndSet(1) + " 请求显示");
            return true;
        }
    }
}
